﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QLBH.DataModel;
using System.Data;
using System.Transactions;

namespace QLBH.Model.Controller
{
    public class HDBanHangController : QLBHEntityBase<HOADONBANHANG>
    {
        public static HDBanHangController GetInstance()
        {
            return new HDBanHangController();
        } 
        public override HOADONBANHANG Add(HOADONBANHANG entity)
        {
            using (TransactionScope tran = new TransactionScope())
            {
                Context.AddToHOADONBANHANGs(entity);

                foreach (HDBHCHITIET hdbhct in entity.HDBHCHITIETs)
                {
                    KHO_MATHANG kho_mh = Kho_MathangController.GetInstance().FindBy(kh =>
                        kh.MHID == hdbhct.MHID).FirstOrDefault();

                    if (kho_mh != null)
                    {
                        kho_mh.SOLUONG -= (int)hdbhct.SOLUONG;

                        Context.ObjectStateManager.ChangeObjectState(kho_mh, EntityState.Modified);
                    }
                }
                Context.SaveChanges();
                tran.Complete();
            }
            return entity;
        }
        public override HOADONBANHANG Edit(HOADONBANHANG entity)
        {
            try
            {
                using (TransactionScope tran = new TransactionScope())
                {
                    //update DBBanHang entity
                    HOADONBANHANG hdbh = FindBy(hd => hd.HDBHID == entity.HDBHID).FirstOrDefault();

                    Delete(hdbh);

                    Add(entity);

                    tran.Complete();
                }

                return entity;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            
        }
    }
}
